<?php

namespace App\Logging;

use Illuminate\Support\Facades\Log;
use Monolog\Formatter\FormatterInterface;

class CustomizeFormatter implements FormatterInterface
{
    /**
     * 处理单条日志记录。
     */
    public function format(array $record): string
    {
        $datetime = $record['datetime']->format('Y-m-d H:i:s');
        $channel = $record['channel'] ?? 'local';
        $level = strtoupper($record['level_name'] ?? 'INFO');
        $message = $record['message'] ?? '';

        $context = $record['context'] ?? [];
        $extra = $record['extra'] ?? [];

        $requestId = $context['requestId'] ?? 'no-request-id';

        unset($context['requestId']);

        $payload = array_filter([
            'context' => $context ?: null,
            'extra' => $extra ?: null,
        ]);

        $payloadString = empty($payload)
            ? ''
            : ' ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        return sprintf(
            '[%s] [%s] [%s] [%s]: %s%s%s',
            $datetime,
            $channel,
            $level,
            $requestId,
            $message,
            $payloadString,
            PHP_EOL
        );
    }

    /**
     * 处理批量日志。
     */
    public function formatBatch(array $records): string
    {
        return array_reduce($records, function ($carry, $record) {
            return $carry . $this->format($record);
        }, '');
    }
}
